#include <my_head.h>

pthread_mutex_t lock;

int money = 1000;
void *task_func_1(void *arg){
    while(1){
        pthread_mutex_lock(&lock); 
        if(money >= 50){
            money -= 50;
            printf("张三取走了50元 还剩 %d 元\n", money);
        }else{
            printf("不够50了 张三取钱失败\n");
            pthread_mutex_unlock(&lock); 
            break;
        }
        pthread_mutex_unlock(&lock); 
        sleep(1);
    }
    pthread_exit(NULL);
}

void *task_func_2(void *arg){
    while(1){
        pthread_mutex_lock(&lock); 
        if(money >= 100){
            money -= 100;
            printf("李四取走了100元 还剩 %d 元\n", money);
        }else{
            printf("不够100了 李四取钱失败\n");
            pthread_mutex_unlock(&lock); 
            break;
        }
        pthread_mutex_unlock(&lock); 
        sleep(1);
    }
    pthread_exit(NULL);
}

int main(int argc, const char *argv[]){

    pthread_mutex_init(&lock, NULL);
    pthread_t tid1, tid2;
    int ret = 0;
    if(0 != (ret = pthread_create(&tid1, NULL, task_func_1, NULL))){
        printf("pthread_create error : [%d] [%s]\n", ret, strerror(ret));
        exit(EXIT_FAILURE);
    }
    if(0 != (ret = pthread_create(&tid2, NULL, task_func_2, NULL))){
        printf("pthread_create error : [%d] [%s]\n", ret, strerror(ret));
        exit(EXIT_FAILURE);
    }
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_mutex_destroy(&lock);
    return 0;
}